package com.wmz.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author wmz
 * @date 2024/7/2 23:07
 * @description 安全用户
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {
    // 商城后台管理系统用户
    private Long userId;
    private String username;
    private String password;
    private Integer status;
    private Long shopId;
    private String loginType;
    private Set<String> perms;

    // 商城购物系统用户
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.loginType + this.userId;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }

    /**
     * 处理一个String字符串中包含多个权限
     * @return
     */
    public Set<String> getPerms() {
        Set<String> finalPerms = new HashSet<>();
        // 循环遍历用户权限集合
        this.perms.forEach(perm -> {
            // 判断权限字符串中是否包含逗号
            if(perm.contains(",")){
                // 包含：说明一个String中有多个权限
                // 拆分权限字符串
                String[] realPerms = perm.split(",");
                for (String realPerm : realPerms) {
                    finalPerms.add(realPerm);
                }
            }else {
                // 不包含：说明一个String中只有一个权限
                finalPerms.add(perm);
            }
        });
        return finalPerms;
    }
}
